<template>
  <div class="note-editor">
    <div class="header-bar">
      <el-button @click="goBack" :icon="ArrowLeft" circle />
      
      <div class="title-section">
        <el-input
          v-model="noteData.title"
          placeholder="请输入笔记标题"
          size="large"
          @input="markAsChanged"
        />
        
        <div class="meta-inputs">
          <el-select
            v-model="noteData.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="添加标签"
            style="width: 100%; margin-top: 8px;"
            @change="markAsChanged"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
          
          <el-checkbox 
            v-model="noteData.isPublic"
            @change="markAsChanged"
            style="margin-top: 8px;"
          >
            公开笔记
          </el-checkbox>
        </div>
      </div>
      
      <div class="actions">
        <el-button 
          @click="saveNote" 
          type="primary" 
          :loading="saving"
          :disabled="!hasChanges"
        >
          <el-icon v-if="!saving"><Check /></el-icon>
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="editor-container">
      <QuillEditor
        v-model="noteData.content"
        placeholder="开始写作..."
        height="100%"
        @change="markAsChanged"
      />
    </div>

    <!-- 状态提示 -->
    <div v-if="lastSaved" class="status-bar">
      <span class="save-status">
        <el-icon><Clock /></el-icon>
        最后保存: {{ formatTime(lastSaved) }}
      </span>
      <span v-if="hasChanges" class="unsaved-indicator">
        · 有未保存的更改
      </span>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading" size="32"><Loading /></el-icon>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Check, Clock, Loading } from '@element-plus/icons-vue'
import QuillEditor from '../components/QuillEditor.vue'
import { useNotesStore } from '../stores/notesApi'
import type { CreateNoteData, UpdateNoteData } from '../services/notes'

const route = useRoute()
const router = useRouter()
const notesStore = useNotesStore()

// 状态
const loading = ref(false)
const saving = ref(false)
const hasChanges = ref(false)
const lastSaved = ref<Date | null>(null)
const originalData = ref<string>('')

// 笔记数据
const noteData = ref<CreateNoteData & { _id?: string }>({
  title: '',
  content: '',
  tags: [],
  isPublic: false
})

// 计算属性
const isNewNote = computed(() => !route.params.id || route.params.id === 'new')
const availableTags = computed(() => notesStore.tags || [])

// 方法
const markAsChanged = () => {
  const currentData = JSON.stringify(noteData.value)
  hasChanges.value = currentData !== originalData.value
}

const saveNote = async () => {
  if (!noteData.value.title.trim()) {
    ElMessage.warning('请输入笔记标题')
    return
  }

  try {
    saving.value = true
    
    if (isNewNote.value) {
      // 创建新笔记
      const result = await notesStore.createNote({
        title: noteData.value.title,
        content: noteData.value.content,
        tags: noteData.value.tags,
        isPublic: noteData.value.isPublic
      })
      
      if (result) {
        noteData.value._id = result._id
        originalData.value = JSON.stringify(noteData.value)
        hasChanges.value = false
        lastSaved.value = new Date()
        ElMessage.success('笔记创建成功')
        
        // 更新URL
        router.replace(`/editor/${result._id}`)
      }
    } else {
      // 更新现有笔记
      const success = await notesStore.updateNote(noteData.value._id!, {
        title: noteData.value.title,
        content: noteData.value.content,
        tags: noteData.value.tags,
        isPublic: noteData.value.isPublic
      })
      
      if (success) {
        originalData.value = JSON.stringify(noteData.value)
        hasChanges.value = false
        lastSaved.value = new Date()
        ElMessage.success('笔记保存成功')
      }
    }
  } catch (error) {
    ElMessage.error('保存失败，请重试')
    console.error('Save failed:', error)
  } finally {
    saving.value = false
  }
}

const loadNote = async () => {
  if (isNewNote.value) return

  try {
    loading.value = true
    const note = await notesStore.getNoteById(route.params.id as string)
    
    if (note) {
      noteData.value = {
        _id: note._id,
        title: note.title,
        content: note.content,
        tags: note.tags || [],
        isPublic: note.isPublic
      }
      originalData.value = JSON.stringify(noteData.value)
      hasChanges.value = false
    } else {
      ElMessage.error('笔记不存在')
      router.push('/notes')
    }
  } catch (error) {
    ElMessage.error('加载笔记失败')
    router.push('/notes')
  } finally {
    loading.value = false
  }
}

const goBack = async () => {
  if (hasChanges.value) {
    try {
      await ElMessageBox.confirm(
        '您有未保存的更改，确定要离开吗？',
        '提示',
        {
          confirmButtonText: '离开',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消
    }
  }
  
  router.push('/notes')
}

const formatTime = (date: Date): string => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 自动保存
let autoSaveTimer: number | null = null

const startAutoSave = () => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
  }
  
  autoSaveTimer = setInterval(() => {
    if (hasChanges.value && !saving.value && noteData.value.title.trim()) {
      saveNote()
    }
  }, 30000) // 30秒自动保存
}

// 生命周期
onMounted(async () => {
  await loadNote()
  startAutoSave()
})

onBeforeUnmount(() => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
  }
})

// 监听路由变化
watch(() => route.params.id, async (newId) => {
  if (newId && newId !== 'new') {
    await loadNote()
  }
})

// 页面离开前确认
window.addEventListener('beforeunload', (e) => {
  if (hasChanges.value) {
    e.preventDefault()
    e.returnValue = ''
  }
})
</script>

<style scoped>
.note-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  overflow: hidden;
}

.header-bar {
  display: flex;
  align-items: flex-start;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  gap: 16px;
  background: #fff;
  flex-shrink: 0;
  z-index: 100;
}

.title-section {
  flex: 1;
  min-width: 0;
}

.meta-inputs {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.status-bar {
  padding: 8px 20px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.save-status {
  display: flex;
  align-items: center;
  gap: 4px;
}

.unsaved-indicator {
  color: #e6a23c;
  font-weight: 500;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-overlay p {
  margin-top: 12px;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-bar {
    padding: 12px 16px;
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-bar > div {
    order: 2;
  }
  
  .header-bar > el-button {
    order: 1;
    align-self: flex-start;
  }
  
  .actions {
    order: 3;
    justify-content: center;
  }
  
  .editor-container {
    padding: 16px;
  }
  
  .meta-inputs {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .header-bar {
    padding: 10px 12px;
  }
  
  .editor-container {
    padding: 12px;
  }
}
</style>